/*jslint browser: true*/
/*global $, jQuery, alert, window*/

function get_create_data() {
    "use strict";
    var search_result_key = window.search_result_key,
        saved_list = window.storage(search_result_key),
        question_dict = {
            "A1": saved_list[window.category_list.getNumByName("A1")],
            "A2": saved_list[window.category_list.getNumByName("A2")],
            "B1": saved_list[window.category_list.getNumByName("B1")],
            "A3": saved_list[window.category_list.getNumByName("A3")],
            "A4": saved_list[window.category_list.getNumByName("A4")]
        },
        random_dict = {
            "A1": window.get_random_list(window.view.A1_choice(),
                                         question_dict.A1.length),
            "A2": window.get_random_list(window.view.A2_choice(),
                                         question_dict.A2.length),
            "B1": window.get_random_list(window.view.B1_choice(),
                                         question_dict.B1.length),
            "A3": window.get_random_list(window.view.A3_choice(),
                                         question_dict.A3.length),
            "A4": window.get_random_list(window.view.A4_choice(),
                                         question_dict.A4.length)
        },
        create_dict = {},
        type_index,
        type_length = window.category_list.length,
        type,
        index,
        length,
        create_data,
        question_index,
        question_id;
    for (type_index = 0; type_index < type_length; type_index += 1) {
        type = window.category_list[type_index];
        create_dict[type + "_list"] = [];
        length = random_dict[type].length;
        for (index = 0; index < length; index += 1) {
            question_index = random_dict[type][index];
            question_id = question_dict[type][question_index].id;
            create_dict[type + "_list"].push(question_id);
        }
    }
    return {
        "major_id": window.major_id,
        "time_limit": window.view.training_time(),
        "name": window.view.training_name(),
        "category_num": 1,
        "id_list_A1": create_dict.A1_list,
        "id_list_A2": create_dict.A2_list,
        "id_list_B1": create_dict.B1_list,
        "id_list_A3": create_dict.A3_list,
        "id_list_A4": create_dict.A4_list,
        "is_active": true
    };
}

window.view = {
    "train_url": function (major_id) {
        "use strict";
        $("#train_url").attr("href", "/major/{id}/index/".format({
            id: major_id
        }));
    },
    "paper_url": function (major_id) {
        "use strict";
        $("#paper_url").attr("href", "/major/{id}/paper/".format({
            id: major_id
        }));
    },
    "history_url_train": function (major_id) {
        "use strict";
        $("#history_url_train").attr("href", "/major/{id}/history/train/".format({
            id: major_id
        }));
    },
    "history_url_paper": function (major_id) {
        "use strict";
        $("#history_url_paper").attr("href", "/major/{id}/history/paper/".format({
            id: major_id
        }));
    },
    "major_title": function (major_name) {
        "use strict";
        $("#major_title").html(major_name);
    },
    "major_crumb": function (major_name) {
        "use strict";
        $("#major_crumb").html(major_name);
    },
    "char_id_list": function (id_list) {
        "use strict";
        var index,
            length,
            char_list;
        //set and get
        if (id_list) {
            $("#char_selection").val(id_list.join(","));
            window.sync.charChecked_select_ztree();
        } else {
            //"".split(",") ==> [""]
            if (!$("#char_selection").val()) { return []; }
            char_list =  $("#char_selection").val().split(",");
            length = char_list.length;
            for (index = 0; index < length; index = index + 1) {
                char_list[index] = parseInt(char_list[index], 10);
            }
            return char_list;
        }
    },
    "training_name": function () {
        "use strict";
        return window.trim($("#training_name").val());
    },
    "training_time": function () {
        "use strict";
        return parseInt(window.trim($("#training_time").val()), 10);
    },
    "A1_choice": function () {
        "use strict";
        return parseInt(window.trim($("#A1_choice").val()), 10);
    },
    "A2_choice": function () {
        "use strict";
        return parseInt(window.trim($("#A2_choice").val()), 10);
    },
    "B1_choice": function () {
        "use strict";
        return parseInt(window.trim($("#B1_choice").val()), 10);
    },
    "A3_choice": function () {
        "use strict";
        return parseInt(window.trim($("#A3_choice").val()), 10);
    },
    "A4_choice": function () {
        "use strict";
        return parseInt(window.trim($("#A4_choice").val()), 10);
    },
    "A1_total": function (total_num) {
        "use strict";
        $("#A1_total").html(total_num);
    },
    "A2_total": function (total_num) {
        "use strict";
        $("#A2_total").html(total_num);
    },
    "B1_total": function (total_num) {
        "use strict";
        $("#B1_total").html(total_num);
    },
    "A3_total": function (total_num) {
        "use strict";
        $("#A3_total").html(total_num);
    },
    "A4_total": function (total_num) {
        "use strict";
        $("#A4_total").html(total_num);
    }
};
window.sync = {
    "char_data_ztree": function () {
        "use strict";
        var major_id = window.major_id,
            char_list_key = '/major/{major_id}/char/'.format({major_id: major_id}),
            char_list = window.fetchData(window.storage(char_list_key), window.format.char),
            index,
            length = char_list.length,
            char_item,
            zNodes = [],
            setting = {
                check: { enable: true  },
                data: {
                    simpleData: { enable: true }
                }
            };
        /*
            data :[ { "id": 1, "name":"", "father_id":0, "is_kp":false, "listorder":""}, 
                    { "id": 2, "name":"", "father_id":0, "is_kp":false, "listorder":""},]}
        zNodes =[   { id:13, pId:1, name:"禁止拖拽 1-3", isParent:true },
                    { id:131, pId:13, name:"禁止拖拽 1-3-1", isParent:true },]
        }*/
        for (index = 0; index < length; index = index + 1) {
            char_item = char_list[index];
            zNodes.push({
                id : char_item.id,
                pId : char_item.father_id,
                name : char_item.name,
                isParent : !char_item.is_kp,
                nocheck: !char_item.is_kp,
                open: true
            });
        }
        $.fn.zTree.init($("#treeDemo"), setting, zNodes);
        window.zTree = $.fn.zTree.getZTreeObj("treeDemo");
    },
    "charChecked_ztree_select" : function () {
        "use strict";
        var treeObj = window.zTree,
            nodes = treeObj.getCheckedNodes(true),
            aList = [],
            index,
            length = nodes.length;
        for (index = 0; index < length; index = index + 1) {
            aList.push(nodes[index].id);
        }
        $("#char_selection").val(aList.join(","));
    },
    "charChecked_select_ztree": function () {
        "use strict";
        //"".split(",") ==> [""]
        if (!$("#char_selection").val()) { return; }
        var checked_id_list = $("#char_selection").val().split(","),
            treeObj = window.zTree,
            index,
            length = checked_id_list.length;
        //zTree
        treeObj.treeObj.checkAllNodes(false);
        for (index = 0; index < length; index = index + 1) {
            treeObj.checkNode(treeObj.getNodeByParam("id", checked_id_list[index]));
        }
    },
    "count_data_html": function (A1, A2, B1, A3, A4) {
        "use strict";
        window.view.A1_total(A1);
        window.view.A2_total(A2);
        window.view.B1_total(B1);
        window.view.A3_total(A3);
        window.view.A4_total(A4);
    }
};
window.init = {
    "global_var": function () {
        "use strict";
        var pathname = location.pathname,
            major_key,
            update_reg = new RegExp('^/major/([0-9]+)/index/$'),
            reg_result_list = update_reg.exec(pathname),
            major_list,
            index,
            length,
            major_item;
        if (reg_result_list) {
            //update question
            window.is_valid = true;
            window.major_id = parseInt(reg_result_list[1], 10);
            major_key = "/major/{id}/".format({id: window.major_id});
            window.zTree = null;
            major_item = window.format.s2c(window.storage(major_key),
                                           window.format.major)[0];
            window.major_name =  major_item.name;
            window.search_result_key = "/major/search/";
        } else {
            throw new Error("网页错误");
        }
    },
    "html_data": function () {
        "use strict";
        window.view.train_url(window.major_id);
        window.view.paper_url(window.major_id);
        window.view.history_url_train(window.major_id);
        window.view.history_url_paper(window.major_id);
        window.view.major_title(window.major_name);
        window.view.major_title(window.major_crumb);
    },
    "ztree_position": function () {
        "use strict";
        var aOffset = $("#char_selection").offset();
        $("#zTreeContainer").css("top", aOffset.top + "px");
        $("#zTreeContainer").css("left", aOffset.left + "px");
        $("#zTreeContainer").css("width", $("#char_selection").width() + "px");
    },
    "char_ztree": function () {
        "use strict";
        window.sync.char_data_ztree();
    },
    "addEventListener": function () {
        "use strict";
        $("#char_selection").click(window.listener.char_select_show);
        $("#zTreeContainer").mouseleave(window.listener.char_select_hide);
        $("#start_training").click(window.listener.start_training);
        window.hideLoading();
    }
};
window.init_func_list = ["global_var",
                         "html_data",
                         "ztree_position",
                         "char_ztree",
                         "addEventListener"];
window.listener = {
    "char_select_show": function () {
        "use strict";
        if ($("#treeDemo").children().length) {
            $("#char_selection").blur();
            $("#zTreeContainer").show("normal");
        }
    },
    "char_select_hide": function () {
        "use strict";
        window.sync.charChecked_ztree_select();
        $("#zTreeContainer").hide("normal");
        window.listener.question_search();
    },
    "question_search": function () {
        "use strict";
        window.loading();
        var question_search_key = "/question/",
            data = {
                char_id_list: window.view.char_id_list()
            };
        $.ajax({
            url: question_search_key,
            type: "PUT",
            dataType: "json",
            async: false,
            data: JSON.stringify(data),
            success: function (result, status) {
                var search_result_key = window.search_result_key,
                    question_list = window.fetchData(result.data, window.format.question),
                    A1_num = window.category_list.getNumByName("A1"),
                    A1_list = [],
                    A1_sub_num = 0,
                    A2_num = window.category_list.getNumByName("A2"),
                    A2_list = [],
                    A2_sub_num = 0,
                    B1_num = window.category_list.getNumByName("B1"),
                    B1_list = [],
                    B1_sub_num = 0,
                    A3_num = window.category_list.getNumByName("A3"),
                    A3_list = [],
                    A3_sub_num = 0,
                    A4_num = window.category_list.getNumByName("A4"),
                    A4_list = [],
                    A4_sub_num = 0,
                    index,
                    length = question_list.length,
                    item,
                    save_list = [];
                for (index = 0; index < length; index = index + 1) {
                    item = question_list[index];
                    switch (item.category_num) {
                    case A1_num:
                        A1_list.push(item);
                        A1_sub_num += item.sub_num;
                        break;
                    case A2_num:
                        A2_list.push(item);
                        A2_sub_num += item.sub_num;
                        break;
                    case B1_num:
                        B1_list.push(item);
                        B1_sub_num += item.sub_num;
                        break;
                    case A3_num:
                        A3_list.push(item);
                        A3_sub_num += item.sub_num;
                        break;
                    case A4_num:
                        A4_list.push(item);
                        A4_sub_num += item.sub_num;
                        break;
                    default:
                        throw new Error("category_num is invalid:" + item.category_num);
                    }
                }
                save_list[A1_num] = A1_list;
                save_list[A2_num] = A2_list;
                save_list[B1_num] = B1_list;
                save_list[A3_num] = A3_list;
                save_list[A4_num] = A4_list;
                window.storage(search_result_key, save_list);
                window.sync.count_data_html(A1_list.length, A2_list.length,
                                            B1_list.length,
                                            A3_list.length, A4_list.length);
                window.hideLoading();
            }
        });
    },
    "start_training": function () {
        "use strict";
        window.loading();
        var create_data = get_create_data();
        $.ajax({
            url:  "/paper/",
            type: "POST",
            dataType: "json",
            async: false,
            data: JSON.stringify(create_data),
            success: function (result, status) {
                var paper_data = window.format.s2c(result.data,
                                                   window.format.paper)[0],
                    paper_id = paper_data.id;
                window.storage("/paper/" + paper_id + "/", result.data);
                window.listener.create_exam(paper_id);
            }
        });
    },
    "create_exam": function (paper_id) {
        "use strict";
        window.loading();
        var paper_key = "/paper/{id}/".format({id: paper_id}),
            paper_data = window.format.s2c(window.storage(paper_key),
                                           window.format.paper)[0],
            detail_key = "/paper/detail/{id}/".format({id: paper_data.detail_id}),
            detail_data = window.format.s2c(window.storage(detail_key),
                                            window.format.detail)[0],
            exam_create_data = {
                "detail_id": detail_data.id,
                "major_id": paper_data.major_id,
                "paper_id": paper_data.id,
                "name": paper_data.name,
                "time_limit": paper_data.time_limit,
                "category_num": paper_data.category_num
            };
        $.ajax({
            url:  "/exam/",
            type: "POST",
            dataType: "json",
            async: false,
            data: JSON.stringify(exam_create_data),
            success: function (result, status) {
                var exam_data = window.format.s2c(result.data,
                                                  window.format.exam)[0];
                window.exam_key = "/exam/{exam_id}/".format({
                    exam_id: exam_data.id
                });
                window.exam_url = "/exam/{exam_id}/exam/".format({
                    exam_id: exam_data.id
                });
                window.storage(window.exam_key, result.data);
                window.open(window.exam_url);
                window.hideLoading();
            }
        });
    }
};